<?php
/**
 * MultiSellerController.php
 *
 * @copyright  2023 beikeshop.com - All Rights Reserved
 * @link       https://beikeshop.com
 * @author     Edward Yang <yangjin@guangda.work>
 * @created    2023-05-26 18:46:38
 * @modified   2023-05-26 18:46:38
 */

namespace Plugin\MultiSeller\Http\Controllers\Admin;

use Beike\Admin\Http\Controllers\Controller;
use Beike\Models\Page;
use Beike\Models\Plugin;
use Beike\Repositories\SettingRepo;
use Beike\Admin\Repositories\PageRepo;
use Beike\Seller\Repositories\SellerRepo;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class MultiSellerController extends Controller
{
    public function index()
    {
        $plugin = app('plugin')->getPluginOrFail('multi_seller');
        $productApproveDefault = $plugin->getSetting('product_approve_default');
        $account_page_id = $plugin->getSetting('account_page_id') ?? '';
        $account_page_name = Page::query()->find($account_page_id)->description->title ?? '';
        $data = [
            'plugin' => $plugin,
            'account_page_name' => $account_page_name,
            'product_approve_except' => SellerRepo::getSellersByProductApprove(!$productApproveDefault),
        ];
        return view('MultiSeller::admin.setting', $data);
    }

    /**
     * @param Request $request
     * @return JsonResponse
     */
    public function saveSetting(Request $request)
    {
        SettingRepo::update('plugin', 'multi_seller', $request->except(['product_approve_except']));
        $productApproveExceptIds = $request->get('product_approve_except', []);
        SellerRepo::updateFieldProductApprove($request->get('product_approve_default'), $productApproveExceptIds);

        return redirect(admin_route('seller_settings.save'))->with('success', trans('common.updated_success'));
    }
}
